package org.come.login;

import com.gl.util.ServerUtil;
import com.tool.Stall.Stall;
import com.tool.tcp.Sprite;
import com.tool.tcpimg.LoginTipBox;
import org.come.bean.*;
import org.come.entity.RegionResult;
import org.come.entity.RoleTableList;
import org.come.entity.RoleTableNew;
import org.come.entity.ServerInfo;
import org.come.model.Configure;
import org.come.socket.Agreement;
import org.come.socket.GameClient;
import org.come.socket.SendMessageUntil;
import org.come.test.Main;
import org.come.until.*;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录界面 选区界面 角色界面 种族界面 创建角色界面
 */
public class LoginJpanel extends JPanel {
    //private MainView mainView;// 游戏开始界面
    private LoginView loginView;// 登录界面
    private AreaView areaView;// 选区界面
    private RoleView roleView;// 角色界面
    private RaceView raceView;// 种族界面
    private CreateView createView;// 创建角色界面
    private int ViewId;// 当前所处界面
    //	private GuideView guideView;
    private RoleTableList roleArr;
    private BigDecimal user_id;
    private String username;
    private String userpwd;
    private int Selected;// 选中的角色信息位置
    /**
     * HGC-2020-03-02
     */
    private String login_uid;// 登录成功后返回的userid
    private String ra_id;//区ID
    public static ServerInfo serverInfo;
    private String msg;//
    private Stall stall;

    private Integer mainY = Integer.valueOf(0);
    private Boolean interfaceScrolling = Boolean.valueOf(false);
    private Boolean loginViewInterfaceScrolling = Boolean.valueOf(false);
    private Boolean aramViewInterfaceScrolling = Boolean.valueOf(false);
    private Boolean ZhuViewInterfaceScrolling = Boolean.valueOf(false);
    public List<RegionResult> regionResultList = new ArrayList();
    private JLabel mouse;
    boolean isBox = false;
    // 限制消息提示数量，避免内存泄漏
    private List<LoginTipBox> SystemPrompt = new ArrayList<>();
    private static final int MAX_PROMPT_MESSAGES = 40; // 限制最大消息数

    private LoginInfo loginInfo;

    private LoginRoleInfo roleInfo;

    public static String Rip = "81.70.235.33";//热更新IP
    public static String Rport = "8088";//热更新端口

    // 使用静态Map优化种族ID查找，避免每次都创建BigDecimal对象
    private static final Map<String, BigDecimal> SPECIES_ID_MAP = new HashMap<>();
    private static final Map<Integer, String> LEI_PATH_MAP = new HashMap<>();

    static {
        // 初始化种族ID映射
        SPECIES_ID_MAP.put("逍遥生", BigDecimal.valueOf(20001));
        SPECIES_ID_MAP.put("剑侠客", BigDecimal.valueOf(20002));
        SPECIES_ID_MAP.put("猛壮士", BigDecimal.valueOf(20003));
        SPECIES_ID_MAP.put("飞燕女", BigDecimal.valueOf(20004));
        SPECIES_ID_MAP.put("英女侠", BigDecimal.valueOf(20005));
        SPECIES_ID_MAP.put("俏千金", BigDecimal.valueOf(20006));
        SPECIES_ID_MAP.put("飞剑侠", BigDecimal.valueOf(20007));
        SPECIES_ID_MAP.put("燕山雪", BigDecimal.valueOf(20008));
        SPECIES_ID_MAP.put("纯阳子", BigDecimal.valueOf(20009));
        SPECIES_ID_MAP.put("红拂女", BigDecimal.valueOf(20010));
        SPECIES_ID_MAP.put("神秀生", BigDecimal.valueOf(20011));
        SPECIES_ID_MAP.put("玲珑女", BigDecimal.valueOf(20012));
        SPECIES_ID_MAP.put("虎头怪", BigDecimal.valueOf(21001));
        SPECIES_ID_MAP.put("夺命妖", BigDecimal.valueOf(21002));
        SPECIES_ID_MAP.put("巨魔王", BigDecimal.valueOf(21003));
        SPECIES_ID_MAP.put("小蛮妖", BigDecimal.valueOf(21004));
        SPECIES_ID_MAP.put("骨精灵", BigDecimal.valueOf(21005));
        SPECIES_ID_MAP.put("狐美人", BigDecimal.valueOf(21006));
        SPECIES_ID_MAP.put("逆天魔", BigDecimal.valueOf(21007));
        SPECIES_ID_MAP.put("媚灵狐", BigDecimal.valueOf(21008));
        SPECIES_ID_MAP.put("混天魔", BigDecimal.valueOf(21009));
        SPECIES_ID_MAP.put("九尾狐", BigDecimal.valueOf(21010));
        SPECIES_ID_MAP.put("绝影魔", BigDecimal.valueOf(21011));
        SPECIES_ID_MAP.put("霜月灵", BigDecimal.valueOf(21012));
        SPECIES_ID_MAP.put("神天兵", BigDecimal.valueOf(22001));
        SPECIES_ID_MAP.put("智圣仙", BigDecimal.valueOf(22002));
        SPECIES_ID_MAP.put("龙战将", BigDecimal.valueOf(22003));
        SPECIES_ID_MAP.put("精灵仙", BigDecimal.valueOf(22004));
        SPECIES_ID_MAP.put("舞天姬", BigDecimal.valueOf(22005));
        SPECIES_ID_MAP.put("玄剑娥", BigDecimal.valueOf(22006));
        SPECIES_ID_MAP.put("武尊神", BigDecimal.valueOf(22007));
        SPECIES_ID_MAP.put("玄天姬", BigDecimal.valueOf(22008));
        SPECIES_ID_MAP.put("紫薇神", BigDecimal.valueOf(22009));
        SPECIES_ID_MAP.put("霓裳仙", BigDecimal.valueOf(22010));
        SPECIES_ID_MAP.put("青阳使", BigDecimal.valueOf(22011));
        SPECIES_ID_MAP.put("云中君", BigDecimal.valueOf(22012));
        SPECIES_ID_MAP.put("祭剑魂", BigDecimal.valueOf(23001));
        SPECIES_ID_MAP.put("猎魂引", BigDecimal.valueOf(23002));
        SPECIES_ID_MAP.put("无崖子", BigDecimal.valueOf(23003));
        SPECIES_ID_MAP.put("墨衣行", BigDecimal.valueOf(23004));
        SPECIES_ID_MAP.put("夜溪灵", BigDecimal.valueOf(23005));
        SPECIES_ID_MAP.put("幽梦影", BigDecimal.valueOf(23006));
        SPECIES_ID_MAP.put("南冠客", BigDecimal.valueOf(23007));
        SPECIES_ID_MAP.put("镜花影", BigDecimal.valueOf(23008));
        SPECIES_ID_MAP.put("沧浪君", BigDecimal.valueOf(24001));
        SPECIES_ID_MAP.put("龙渊客", BigDecimal.valueOf(24002));
        SPECIES_ID_MAP.put("忘忧子", BigDecimal.valueOf(24003));
        SPECIES_ID_MAP.put("骊珠儿", BigDecimal.valueOf(24004));
        SPECIES_ID_MAP.put("木兰行", BigDecimal.valueOf(24005));
        SPECIES_ID_MAP.put("莫解语", BigDecimal.valueOf(24006));
        SPECIES_ID_MAP.put("游无极", BigDecimal.valueOf(24007));
        SPECIES_ID_MAP.put("临九渊", BigDecimal.valueOf(24008));

        // 初始化族路径映射
        LEI_PATH_MAP.put(0, "人");
        LEI_PATH_MAP.put(1, "魔");
        LEI_PATH_MAP.put(2, "仙");
        LEI_PATH_MAP.put(3, "鬼");
        LEI_PATH_MAP.put(4, "龙");
    }

    public LoginJpanel(LoginInfo loginInfo) {
        // 键盘监听
        this.setLayout(null);
        this.setPreferredSize(new Dimension(1016, 710));
        /** HGC-2020-03-02 */
        //============================== 这一块敌方是设置大区信息的, 多个区就设置多个信息
        List<RegionResult> regionResultList = new ArrayList();
//		服务器 服务器IP 这里就是改IP的 服务器里看下

//先出jar包 然后出登录器org.come.test.Main 再出多开器Main.main
// 创建一个RegionResult对象
        RegionResult reg3 = new RegionResult();
// 设置RA_ID
        reg3.setRA_ID(new BigDecimal("100"));
// 设置RA_NAME
        reg3.setRA_NAME("一区");
// 设置RA_NAME
        reg3.setRA_NAME("大唐盛世");
// 设置IP
        reg3.setIp("81.70.235.33");
// 设置端口
        reg3.setPort(ServerUtil.PORT);
// 设置Dowport
        reg3.setDowport(ServerUtil.SERVER_PORT);
// 设置IfNew
        reg3.setIfNew("3");
// 将RegionResult对象添加到Util.regionResultList中
        Util.regionResultList.add(reg3);

        RegionResult reg4 = new RegionResult();
        reg4.setRA_ID(new BigDecimal("100"));
        reg4.setRA_NAME("二区");
        reg4.setRA_NAME("红木修复");
        reg4.setIp("202.189.6.113");
        reg4.setPort(7101);
        reg4.setDowport("8083");
        reg4.setIfNew("3");
        Util.regionResultList.add(reg4);

        try {
            mouse = new JLabel() {
                @Override
                protected void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    if (isBox) {
                        int chatY = (int) this.getHeight() / 2 - 50;
                        g.translate(0, chatY);
                        for (int i = SystemPrompt.size() - 1; i >= 0; i--) {
                            LoginTipBox chatPanel = SystemPrompt.get(i);
                            if (chatPanel.IsTime()) {
                                g.translate(0, -chatPanel.getHeight());
                                chatY -= chatPanel.getHeight();
                                chatPanel.paint(g);
                            } else {
                                SystemPrompt.remove(i);
                            }
                        }
                        g.translate(0, -chatY);
                        if (SystemPrompt.size() == 0) {
                            isBox = false;
                        }
                    }

                    Sprite mouse = MessagrFlagUntil.getMouse();
                    if (mouse != null) {
                        PathPoint point = mousepath();
                        mouse.updateToTime(System.currentTimeMillis(), 0);
                        mouse.draw(g, point.getX(), point.getY());
                    }
                }
            };
        } catch (Exception e) {
            e.printStackTrace();
        }

        framechange(1, Util.regionResultList, loginInfo);

        try {
            // 连接账号服务器
//            SendMessageUntil.accServerKey = SendMessageUntil.loginIp + "|" + SendMessageUntil.loginPort;
//            SendMessageUntil.getClientUntil(SendMessageUntil.loginIp, SendMessageUntil.loginPort, "login");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void LoadServerInfo() throws IOException {
        //system.out.println("The method received in the request-line is known by the origin server supported by the target resource.");
//		setServerInfo((ServerInfo) GsonUtil.getGsonUtil().getgson().fromJson(
//				AESUtil.AESJDKDncode(CreateTextUtil.getContent("jre/lib/net.jar"), ">LA~h4FNKPMJW099vd0999"),
//				ServerInfo.class));
    }

    public void addPrompt(String text) {
        if (text != null) {
            // 限制消息数量，避免内存泄漏
            if (SystemPrompt.size() >= MAX_PROMPT_MESSAGES) {
                SystemPrompt.remove(0); // 移除最早的消息
            }
            SystemPrompt.add(new LoginTipBox(text));
            isBox = true;
        }
    }

    /**
     * 进入游戏
     */
    public void intoGame() {
        if (roleArr == null) {
            return;
        }
        RoleTableNew tableNew = null;
        if (Selected >= roleArr.getRoleList().size()) {
            if (roleArr.getRoleList().size() != 0) {
                tableNew = roleArr.getRoleList().get(0);
            }
        } else {
            tableNew = roleArr.getRoleList().get(Selected);
        }
        if (tableNew == null) {
            return;
        }
        ConfigureBean allConfigure = UserMessUntil.getConfigureBean();
        Map<BigDecimal, Configure> item = allConfigure.getAllConfigure();
        Configure configure = item.get(new BigDecimal(1));
        if ("1".equals(configure.getSfdkms())) {
            if (tableNew.getGameTimeRemaining() != null && tableNew.getGameTimeRemaining() <= 0) {
                return;
            }
        }
        String sendmes = Agreement.getAgreement().enterGameAgreement(tableNew.getRole_id().toString());
        SendMessageUntil.toServer(sendmes);
    }

    private PathPoint pathPoint = new PathPoint(0, 0);

    public PathPoint mousepath() {
        Point p = MouseInfo.getPointerInfo().getLocation();
        Point p1 = Main.frame.getLocation();
        pathPoint.setX((int) (p.getX() - p1.getX() - 4));
        pathPoint.setY((int) (p.getY() - p1.getY() - 26));
        return pathPoint;
    }

    /**
     * 创建角色
     */
    public void createRole() {
        if (this.roleArr.getRoleList().size() >= 5) {
            this.createView.setMsg("你角色已经有5个了");
        } else {
            String roleName = this.createView.getTextAccount().getText();
            if (!Util.special(roleName)) {
                this.createView.setMsg("角色名字不能包含特殊字符!!");
            } else if (!Util.isIllegal(roleName)) {
                this.createView.setMsg("名称中包含非法字符！！");
            } else if ("".equals(roleName)) {
                this.createView.setMsg("你没有输入名称");
            } else {
                // 优化角色名重复检查
                for (RoleTableNew role : this.roleArr.getRoleList()) {
                    if (roleName.equals(role.getRolename())) {
                        this.createView.setMsg("你名称已重复");
                        return;
                    }
                }

                int size = 0;
                char[] nz = roleName.toCharArray();

                for (char c : nz) {
                    String loginResult = String.valueOf(c);
                    if (loginResult.getBytes().length == 1) {
                        ++size;
                    } else {
                        size += 2;
                    }
                }

                if (size > 12) {
                    this.createView.setMsg("角色名字超长了!!！");
                } else {
                    this.createView.setMsg(null);
                    BigDecimal var7 = getSpeciesId(this.createView.SelectedRole());
                    ControlNpcXmlUntil.setSpeciesId(var7.toString());
                    ControlNpcXmlUntil.GetXmlPath("roleState.xml");
                    LoginResult var8 = ControlNpcXmlUntil.getLoginResult();
                    var8.setUser_id(new BigDecimal(this.login_uid));
                    var8.setSpecies_id(var7);
                    var8.setRolename(roleName);
                    var8.setTitle(GameClient.BT + "一员");
                    var8.setServerMeString(this.ra_id);
                    String serverMes = Agreement.getAgreement().createRoleAgreement(GsonUtil.getGsonUtil().getgson().toJson(var8));
                    SendMessageUntil.toServer(serverMes);
                }
            }
        }
    }

    /**
     * 选中
     */
    public void loginSelected(int i) {
        this.Selected = i;
        roleView.xz(roleArr.getRoleList().get(i), i);
    }

    /**
     * 登录成功
     */
    public void loginSuccess(RoleTableList roleArr) {
        this.roleArr = roleArr;
        if (this.roleArr.getRoleList().size() != 0) {
            this.user_id = this.roleArr.getRoleList().get(0).getUser_id();
            if (this.roleArr.getRoleList().get(0).getGrade() == null || this.roleArr.getRoleList().get(0).getRolename() == null) {
                this.roleArr.getRoleList().remove(0);
            }
        }
        this.Selected = 0;
        framechange(2, null, null);
    }

    /**
     * 种族选中
     */
    public void raceSelected(int i) {
        quxiao(raceView.getLeis(), -1);
        if (createView == null) {
            createView = new CreateView(this, i);
        } else {
            createView.xzRace(i, this);
            createView.xzRole(0);
        }
        framechange(4, null, null);
    }

    /**
     * 切换界面 -1回退 0登录 1选区 2角色 3种族 4创建角色
     */
    public void framechange(int id, List<RegionResult> regionResultList, LoginInfo loginInfo) {
        if (id == -1) {
            if (ViewId == 2) {
                framechange(1, null, null);
            } else if (ViewId == 3) {
                framechange(2, null, null);
            } else if (ViewId == 4) {
                framechange(3, null, null);
            }
            return;
        }
        this.ViewId = id;

        // 优化界面切换逻辑，减少重复代码
        cleanupViews();

        switch (ViewId) {
            case 5:
                // 主界面逻辑
                break;
            case 0: // 登录界面
                if (loginView == null) {
                    loginView = new LoginView(this);
                }
                add(loginView);
                break;
            case 1: // 选区界面
                if (areaView == null) {
                    areaView = new AreaView(Util.regionResultList, loginInfo, this);
                }
                add(areaView);
                break;
            case 2: // 角色界面
                if (roleView == null) {
                    roleView = new RoleView(this);
                } else {
                    roleView.sx(roleArr, this);
                }
                add(roleView);
                break;
            case 3: // 种族界面
                if (raceView == null) {
                    raceView = new RaceView(this);
                }
                add(raceView);
                break;
            case 4: // 创建角色界面
                if (createView == null) {
                    createView = new CreateView(this);
                }
                add(createView);
                break;
        }
    }

    /**
     * 清理不需要的视图组件
     */
    private void cleanupViews() {
        if (loginView != null && ViewId != 0) {
            remove(loginView);
            loginView = null;
        }
        if (areaView != null && ViewId != 1) {
            remove(areaView);
            areaView = null;
        }
        if (roleView != null && ViewId != 2) {
            remove(roleView);
            roleView = null;
        }
        if (raceView != null && ViewId != 3) {
            remove(raceView);
            raceView = null;
        }
        if (createView != null && ViewId != 4) {
            remove(createView);
            createView = null;
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        try {
            // 保持原有的sleep机制来控制动画速度
            if (ViewId == 0 && loginView != null && loginView.getRegisterView() != null && loginView.getRegisterView().isVisible()) {
                Thread.sleep(100); // 注册界面动画较慢
            } else {
                Thread.sleep(20);  // 其他界面正常速度
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 保持原有的界面切换逻辑
        if ((this.loginViewInterfaceScrolling.booleanValue()) && (this.loginView != null)) {
            this.mainY = Integer.valueOf(this.mainY.intValue() - 40);
            this.loginView.setBounds(this.loginView.getX(), this.mainY.intValue(), this.loginView.getWidth(), this.loginView.getHeight());
            if (Math.abs(this.mainY.intValue()) > this.loginView.getHeight()) {
                remove(this.loginView);
                this.loginView = null;
                this.loginViewInterfaceScrolling = Boolean.valueOf(false);
                this.mainY = Integer.valueOf(0);
            }
        }
        if ((this.aramViewInterfaceScrolling.booleanValue()) && (this.areaView != null)) {
            this.mainY = Integer.valueOf(this.mainY.intValue() - 40);
            this.areaView.setBounds(this.areaView.getX(), this.mainY.intValue(), this.areaView.getWidth(), this.areaView.getHeight());
            if (Math.abs(this.mainY.intValue()) > this.areaView.getHeight()) {
                remove(this.areaView);
                this.areaView = null;
                this.aramViewInterfaceScrolling = Boolean.valueOf(false);
                this.mainY = Integer.valueOf(0);
            }
        }
        if ((this.ZhuViewInterfaceScrolling.booleanValue()) && (this.roleView != null)) {
            this.mainY = Integer.valueOf(this.mainY.intValue() - 40);
            this.roleView.setBounds(this.roleView.getX(), this.mainY.intValue(), this.roleView.getWidth(), this.roleView.getHeight());
            if (Math.abs(this.mainY.intValue()) > this.roleView.getHeight()) {
                remove(this.roleView);
                this.roleView = null;
                this.aramViewInterfaceScrolling = Boolean.valueOf(false);
                this.mainY = Integer.valueOf(0);
            }
        }

        // 保持原有的重绘机制
        repaint();
    }

    public LoginView getLoginView() {
        return loginView;
    }

    public void setLoginView(LoginView loginView) {
        this.loginView = loginView;
    }

    public AreaView getAreaView() {
        return areaView;
    }

    public void setAreaView(AreaView areaView) {
        this.areaView = areaView;
    }

    public RoleView getRoleView() {
        return roleView;
    }

    public void setRoleView(RoleView roleView) {
        this.roleView = roleView;
    }

    public RaceView getRaceView() {
        return raceView;
    }

    public void setRaceView(RaceView raceView) {
        this.raceView = raceView;
    }

    public CreateView getCreateView() {
        return createView;
    }

    public void setCreateView(CreateView createView) {
        this.createView = createView;
    }

    public RoleTableList getRoleArr() {
        return roleArr;
    }

    public void setRoleArr(RoleTableList roleArr) {
        this.roleArr = roleArr;
    }

    public String getLogin_uid() {
        return login_uid;
    }

    public void setLogin_uid(String login_uid) {
        this.login_uid = login_uid;
    }

    public String getRa_id() {
        return ra_id;
    }

    public void setRa_id(String ra_id) {
        this.ra_id = ra_id;
    }

    public String getUserpwd() {
        return userpwd;
    }

    public void setUserpwd(String userpwd) {
        this.userpwd = userpwd;
    }

    public static ServerInfo getServerInfo() {
        return serverInfo;
    }

    public static void setServerInfo(ServerInfo serverInfo) {
        LoginJpanel.serverInfo = serverInfo;
    }

    /**
     * 将指定按钮为选中 取消其他按钮的点击效果
     */
    public static void quxiao(SpriteBtn[] btns, int zhi) {
        if (btns != null) {
            for (int i = 0; i < btns.length; i++) {
                if (btns[i] != null) {
                    if (i == zhi) {
                        btns[i].btn(2);
                    } else {
                        btns[i].btn(0);
                    }
                }
            }
        }
    }

    /**
     * 获取族按钮的路径
     */
    public static String leipath(int i) {
        return LEI_PATH_MAP.getOrDefault(i, "人");
    }

    /**
     * 根据名称获取种族id
     */
    public static BigDecimal getSpeciesId(String name) {
        return SPECIES_ID_MAP.getOrDefault(name, BigDecimal.valueOf(20001));
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public int getViewId() {
        return ViewId;
    }

    public void setViewId(int viewId) {
        ViewId = viewId;
    }

    public BigDecimal getUser_id() {
        return user_id;
    }

    public void setUser_id(BigDecimal user_id) {
        this.user_id = user_id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getSelected() {
        return Selected;
    }

    public void setSelected(int selected) {
        Selected = selected;
    }

    public Stall getStall() {
        return stall;
    }

    public void setStall(Stall stall) {
        this.stall = stall;
    }

    public Integer getMainY() {
        return mainY;
    }

    public void setMainY(Integer mainY) {
        this.mainY = mainY;
    }

    public Boolean getInterfaceScrolling() {
        return interfaceScrolling;
    }

    public void setInterfaceScrolling(Boolean interfaceScrolling) {
        this.interfaceScrolling = interfaceScrolling;
    }

    public Boolean getLoginViewInterfaceScrolling() {
        return loginViewInterfaceScrolling;
    }

    public void setLoginViewInterfaceScrolling(Boolean loginViewInterfaceScrolling) {
        this.loginViewInterfaceScrolling = loginViewInterfaceScrolling;
    }

    public Boolean getAramViewInterfaceScrolling() {
        return aramViewInterfaceScrolling;
    }

    public void setAramViewInterfaceScrolling(Boolean aramViewInterfaceScrolling) {
        this.aramViewInterfaceScrolling = aramViewInterfaceScrolling;
    }

    public Boolean getZhuViewInterfaceScrolling() {
        return ZhuViewInterfaceScrolling;
    }

    public void setZhuViewInterfaceScrolling(Boolean zhuViewInterfaceScrolling) {
        ZhuViewInterfaceScrolling = zhuViewInterfaceScrolling;
    }

    public List<RegionResult> getRegionResultList() {
        return regionResultList;
    }

    public void setRegionResultList(List<RegionResult> regionResultList) {
        this.regionResultList = regionResultList;
    }

    public LoginInfo getLoginInfo() {
        return loginInfo;
    }

    public void setLoginInfo(LoginInfo loginInfo) {
        this.loginInfo = loginInfo;
    }

    public void setRoleInfo(LoginRoleInfo roleInfo) {
        this.roleInfo = roleInfo;
    }
}